package com.sdp.wx.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActHiComment;
import com.sdp.flow.db.service.IWorkflowService;
import com.sdp.flow.dto.FlowParam;
import com.sdp.flow.utils.FlowConstants;
import com.sdp.wx.db.wx_assets_enable.entity.WxAssetsEnable;
import com.sdp.wx.db.wx_assets_enable.service.IWxAssetsEnableService;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.WxConstants;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-03-01
 */
@RestController
@RequestMapping("/WxAssetsEnableController")
public class WxAssetsEnableController {

	@Autowired
	private Query query;
	
	@Autowired
	private IWxAssetsEnableService assetsEnableService;
	
	@Autowired
	private CurrentLoginEmp currentLoginEmp;
	
	@Autowired
	private IWorkflowService workflowService;
	
	public static final String 启用报告模版 = "process_741bzg3a";
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(assetsEnableService, WxAssetsEnable.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody WxAssetsEnable report) {
		if(report == null){
			return Result.error("信息为空");
		}
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if (emp == null || !emp.containsKey("empNo")) {
			return Result.error("当前登录人信息为空");
		}
		if(StringUtils.isEmpty(report.getKeyId())) {
			//report.setReportCode(SequenceNoUtils.getSequenceNo(SequenceNoUtils.固定资产申请单));
			report.setApproveStatus(WxConstants.流程审批状态_未提交.getCode());
			report.setEmpNo(emp.getString("empNo"));
			report.setEmpName(emp.getString("empName"));
			report.setCreateTime(LocalDateTime.now());
			assetsEnableService.save(report);

		} else {
			assetsEnableService.updateById(report);
		}
		
		return Result.ok(report);
	}
	
	@PostMapping(value = "/saveAndStartFlow")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> saveAndStartFlow(@RequestBody WxAssetsEnable report) {
		if(report == null){
			return Result.error("信息为空");
		}
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if (emp == null || !emp.containsKey("empNo")) {
			return Result.error("当前登录人信息为空");
		}
		if(StringUtils.isEmpty(report.getKeyId())) {
			//report.setReportCode(SequenceNoUtils.getSequenceNo(SequenceNoUtils.固定资产申请单));
			report.setApproveStatus(WxConstants.流程审批状态_未提交.getCode());
			report.setEmpNo(emp.getString("empNo"));
			report.setEmpName(emp.getString("empName"));
			report.setCreateTime(LocalDateTime.now());
			assetsEnableService.save(report);

		} else {
			assetsEnableService.updateById(report);
		}
		//处理流程信息
		report.setTemplateId(启用报告模版);
		report.setApproveStatus(WxConstants.流程审批状态_审批中.getCode());
		//发起流程
		FlowParam flowParam = new FlowParam();
		flowParam.setUserId(emp.getString("empNo"));
		flowParam.setTemplateId(report.getTemplateId());
		flowParam.setBizId(report.getKeyId());
		//指定审批人
		Map<String, Object> variableMap = new HashMap<>();
		variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, report.getApprover());
		flowParam.setVariableMap(variableMap);
		//启动工作流
		String instanceId = workflowService.startFlowAndCommit(flowParam);
		if (StringUtils.isEmpty(instanceId)) {
			throw new RuntimeException("流程启动失败!");
		}
		
		//发起成功设置流程实例Id
		report.setInstanceId(instanceId);
		assetsEnableService.updateById(report);
		
		return Result.ok(report);
	}
	
	/**
	 * 流程提交
	 * @param contract
	 * @return
	 */
	@PostMapping(value = "/commit")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> commit(@RequestBody WxAssetsEnable report) {
		if(report == null){
			return Result.error("信息为空");
		}
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if (emp == null || !emp.containsKey("empNo")) {
			return Result.error("当前登录人信息为空");
		}
		//提交流程
		if (StringUtils.isEmpty(report.getTaskId())) {
			return Result.error("流程信息不完整");
		}
		FlowParam flowParam = new FlowParam();
		flowParam.setUserId(emp.getString("empNo"));
		
		flowParam.setTaskId(report.getTaskId());

		//流程提交参数
		Map<String, Object> variableMap = new HashMap<>();
		variableMap.put("isPass", report.getIsPass());
		variableMap.put("link", report.getLink());
		variableMap.put("userName", emp.getString("empName"));
		variableMap.put("userAvatar", emp.getString("profilePicture"));
		variableMap.put("userSign", emp.getString("nameSign"));
		//设置流程表单对象
		variableMap.put("flowData", report);
		if (!StringUtils.isEmpty(report.getIsPass())) {

			if (WxConstants.否.getCode().equals(report.getIsPass())) {
				variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, report.getEmpNo());
				if(StringUtils.isEmpty(report.getApprovalOpinion())){
					report.setApprovalOpinion("不同意");
				}
				report.setApproveStatus(WxConstants.流程审批状态_驳回.getCode());
			}else {
				if(StringUtils.isEmpty(report.getApprovalOpinion())){
					report.setApprovalOpinion("同意");
				}
				variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, report.getApprover());
				report.setApproveStatus(WxConstants.流程审批状态_审批中.getCode());
			}
			
			flowParam.setVariableMap(variableMap);
			
			//更新审批人列表
			report.setApproversList((report.getApproversList()==null?"":report.getApproversList())+("["+emp.getString("empNo")+"]"));

		}
		
		if (!StringUtils.isEmpty(report.getApprovalOpinion())) {
			flowParam.setOpinion(report.getApprovalOpinion());
		}
		
		assetsEnableService.updateById(report);
		workflowService.commitTask(flowParam);
		
		return Result.ok(report);
	}
	
	/**
	 * 流程撤销
	 * @param instanceId
	 * @return
	 */
	@GetMapping(value = "/cancel")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> cancel(@RequestParam(name="instanceId",required=true) String instanceId) {
		LambdaQueryWrapper<WxAssetsEnable> query = new LambdaQueryWrapper<>();
		query.eq(WxAssetsEnable::getInstanceId, instanceId);
		WxAssetsEnable report = assetsEnableService.getOne(query);
		if(report==null) {
			return Result.error("信息不存在，不能进行撤销");
		}
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if(!report.getEmpNo().equals(emp.getString("empNo"))) {
			return Result.error("不是填写人，不能进行撤销操作");
		}
		
		//流程撤销
		workflowService.stopFlow(instanceId, "撤销");
		
		assetsEnableService.removeById(report.getKeyId());
		return Result.ok(report.getKeyId());
	}
	
	@RequestMapping(value="/queryByInstanceId")
	public Result<?> queryByInstanceId(@RequestParam String instanceId) {
		if (StringUtils.isEmpty(instanceId)) {
			return Result.error("instanceId不能为空!");
		}
		QueryWrapper<WxAssetsEnable> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(WxAssetsEnable::getInstanceId, instanceId);
		WxAssetsEnable report = assetsEnableService.getOne(queryWrapper, false);
		List<ActHiComment> commentList = workflowService.getApprovedOpinionNew(instanceId);
		report.setApprovalOpinions(commentList);
		return Result.ok(report);
	}
	
}

